package com.lau.utils;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lau.constant.Constant;
import com.lau.vo.PagingData;
import com.lau.vo.PagingParams;
import com.lau.vo.SortField;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author:Lau
 * @create: 2022-12-19 10:37
 * @Description: 分页工具
 */
@Data
@NoArgsConstructor
public class PageUtils {
    /**
     * 获取分页对象
     * @param params      分页查询参数
     */
    public static <T> IPage<T> getPage(PagingParams params) {
        //分页参数
        long curPage = params.getPageIndex();
        long limit = params.getPageSize();

        //分页对象
        Page<T> page = new Page<>(curPage, limit);

        //排序字段
        List<SortField> sortFieldList = params.getSortFieldList();

        //没有排序字段，则不排序
        if(CollectionUtils.isEmpty(sortFieldList)){
            return page;
        }
        List<OrderItem> orderItems = new ArrayList<>();
        for (SortField sortField : sortFieldList) {
            if("asc".equalsIgnoreCase(sortField.getOrderType())&&sortField.getFieldName()!=null){
                orderItems.add(OrderItem.asc(sortField.getFieldName()));
            }
        }
        page.addOrder(orderItems);
        return page;
    }

    public static <T> PagingData<T> getPageData(IPage page,PagingParams params, Class<T> target){
        List<T> targetList = ConvertUtils.sourceToTarget(page.getRecords(), target);
        params.setTotalCount(page.getTotal());
        return new PagingData<T>(params,targetList);
    }

    public static <T> PagingData<T> getPageData(IPage page,PagingParams params, List<T> source){
        params.setTotalCount(page.getTotal());
        return new PagingData<T>(params,source);

    }
}
